#!/usr/bin/env node

/**
 * React 19 兼容性检查脚本
 * 检查项目中是否存在与React 19不兼容的代码模式
 */

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 需要检查的文件模式
const patterns = [
  // 字符串ref
  { pattern: /ref="[^"]*"/g, message: '发现字符串ref，需要迁移到回调函数形式' },
  { pattern: /this\.refs\./g, message: '发现this.refs使用，需要迁移到useRef' },
  
  // 已废弃的Context API
  { pattern: /childContextTypes/g, message: '发现childContextTypes，需要迁移到新的Context API' },
  { pattern: /getChildContext/g, message: '发现getChildContext，需要迁移到新的Context API' },
  { pattern: /contextTypes/g, message: '发现contextTypes，需要迁移到新的Context API' },
  
  // 已废弃的生命周期方法
  { pattern: /componentWillMount/g, message: '发现componentWillMount，需要迁移到componentDidMount或useEffect' },
  { pattern: /componentWillReceiveProps/g, message: '发现componentWillReceiveProps，需要迁移到componentDidUpdate或useEffect' },
  { pattern: /componentWillUpdate/g, message: '发现componentWillUpdate，需要迁移到componentDidUpdate或useEffect' },
  
  // 已废弃的React方法
  { pattern: /React\.createClass/g, message: '发现React.createClass，需要迁移到函数组件或类组件' },
  { pattern: /React\.PropTypes/g, message: '发现React.PropTypes，需要迁移到prop-types包' },
];

// 需要检查的文件扩展名
const fileExtensions = ['.tsx', '.ts', '.jsx', '.js'];

// 递归获取所有文件
function getAllFiles(dirPath, arrayOfFiles = []) {
  const files = fs.readdirSync(dirPath);
  
  files.forEach(file => {
    const fullPath = path.join(dirPath, file);
    if (fs.statSync(fullPath).isDirectory()) {
      // 跳过node_modules和dist目录
      if (!['node_modules', 'dist', '.git'].includes(file)) {
        arrayOfFiles = getAllFiles(fullPath, arrayOfFiles);
      }
    } else {
      const ext = path.extname(file);
      if (fileExtensions.includes(ext)) {
        arrayOfFiles.push(fullPath);
      }
    }
  });
  
  return arrayOfFiles;
}

// 检查单个文件
function checkFile(filePath) {
  const content = fs.readFileSync(filePath, 'utf8');
  const issues = [];
  
  patterns.forEach(({ pattern, message }) => {
    const matches = content.match(pattern);
    if (matches) {
      issues.push({
        file: filePath,
        message,
        matches: matches.length,
        pattern: pattern.toString()
      });
    }
  });
  
  return issues;
}

// 主函数
function main() {
  console.log('🔍 开始React 19兼容性检查...\n');
  
  const srcPath = path.join(__dirname, '..', 'src');
  const files = getAllFiles(srcPath);
  
  let totalIssues = 0;
  const allIssues = [];
  
  files.forEach(file => {
    const issues = checkFile(file);
    if (issues.length > 0) {
      allIssues.push(...issues);
      totalIssues += issues.length;
    }
  });
  
  if (totalIssues === 0) {
    console.log('✅ 恭喜！没有发现React 19兼容性问题。');
  } else {
    console.log(`❌ 发现 ${totalIssues} 个潜在的兼容性问题：\n`);
    
    allIssues.forEach((issue, index) => {
      console.log(`${index + 1}. ${issue.message}`);
      console.log(`   文件: ${issue.file}`);
      console.log(`   匹配次数: ${issue.matches}`);
      console.log(`   模式: ${issue.pattern}\n`);
    });
    
    console.log('💡 建议：');
    console.log('1. 将字符串ref迁移到回调函数形式');
    console.log('2. 将this.refs迁移到useRef Hook');
    console.log('3. 将旧的Context API迁移到新的Context API');
    console.log('4. 将已废弃的生命周期方法迁移到新的生命周期方法');
    console.log('5. 将React.createClass迁移到函数组件或类组件');
  }
  
  console.log('\n📚 React 19升级指南：');
  console.log('https://react.dev/blog/2024/12/05/react-19');
}

// 运行主函数
main();

export { checkFile, getAllFiles, patterns };
